<?php

namespace app\task\command;

use think\facade\Db;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 话费订单状态变更回调
 * @package app\task\command
 */
class MobileNotify extends Command
{
    /**
     * 配置指令
     * 
     * sudo -uwww php /www/wwwroot/api/think mobile:notifyAgent
     */
    protected function configure()
    {
        $this->setName('mobile:notifyAgent')
            ->setDescription('notify order status to agent');
    }

    /**
     * 执行指令
     * @param Input $input
     * @param Output $output
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $start = date('Y-m-d H:i:s');
        echo '话费订单状态变更开始通知了' . PHP_EOL;
        $lockKey = 'mobile_order_notify_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;
            return true;
        }

        cache($lockKey, 1, 120);

        $now = time();
        $list = Db::name('mobile_notify_agent')
            ->where('status', 1)
            ->where('send_time', '<=', $now)
            ->limit(1000)
            ->order('updated_at asc')
            ->select()
            ->toArray();

        $done = 0;
        foreach ($list as $order) {
            $params = json_decode($order['params'], true);
            $appSecret = $params['app_secret'];
            unset($params['app_secret']);
            $params['timestamp'] = $now;
            $params['sign'] = getSign($params, $appSecret);
            $params = json_encode($params);
            $res = curlPost($order['notify_url'], $params, [
                'Content-type: application/json;charset=utf-8'
            ]);
            $update = [
                'result' => $order['result'] . PHP_EOL . date('Y-m-d H:i:s') . PHP_EOL . $res . PHP_EOL,
            ];
            if ($res !== 'SUCCESS' && $res !== 'ok') {
                if ($order['try_times'] >= 2) {
                    $update['status'] = 3;
                } else {
                    $update['status'] = 1;
                    $update['try_times'] = $order['try_times'] + 1;
                    $update['send_time'] = $now + 300;
                }
            } else {
                $done += 1;
                $update['status'] = 2;
            }
            Db::name('mobile_notify_agent')
                ->where('id', $order['id'])
                ->update($update);
        }

        cache($lockKey, null);

        echo '话费订单状态变更通知结束了：成功通知 ' . $done . ' ' . $start . '--' . date('Y-m-d H:i:s') . PHP_EOL;
    }
}
